package com.nsi.service.Impl;


import com.aliyun.oos.demo.AliyunOSSClientUtil;
import com.aliyun.oos.demo.OSSClientConstants;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.nsi.util.RedisUtils;
import com.nsi.common.ServerResponse;
import com.nsi.dao.CommunityUserMapper;
import com.nsi.pojo.CommunityUser;
import com.nsi.pojo.MsgSecCheckJson;
import com.nsi.service.AccessTokenService;
import com.nsi.service.CommunityUserService;
import com.nsi.util.Httpsrequest;
import com.nsi.util.ImageUtil;
import com.nsi.util.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 社区用户 服务实现类
 * </p>
 *
 * @author Li Yan
 * @since 2019-12-13
 */
@Service
@Slf4j
public class CommunityUserServiceImpl extends ServiceImpl<CommunityUserMapper, CommunityUser> implements CommunityUserService {

    private static final String TOKEN_PREFIX = "token_miniProgramPitaya";

    @Autowired
    private CommunityUserMapper communityUserMapper;
    @Autowired
    private AccessTokenService accessTokenService;


    @Override
    public ServerResponse login(String wechatId) {

        EntityWrapper<CommunityUser> wrapper = new EntityWrapper<>();
        wrapper.eq("open_id", wechatId);
        int i = communityUserMapper.selectCount(wrapper);
        if (i == 0) {
            return ServerResponse.createByErrorMessage("未注册");
        } else {
            List<CommunityUser> list = communityUserMapper.selectList(wrapper);
//            更新上次登录时间
            CommunityUser communityUser = new CommunityUser();
            communityUser.setId(list.get(0).getId());
            communityUser.setUpdateTime(new Date());
            communityUserMapper.updateById(communityUser);
            return ServerResponse.createBySuccess("success", list.get(0));
        }
    }

    @Override
    public ServerResponse register(CommunityUser communityUser) {
        //预处理
        communityUser.setTruename("");
        communityUser.setUsermail("");
        communityUser.setPhone("");
        communityUser.setSlogan("");
        communityUser.setOrganization("");
        communityUser.setPosition("");
        communityUser.setPassword("");

        communityUser.setCreateTime(new Date());
        communityUser.setUpdateTime(new Date());
        communityUser.setGradeSign(1);

        if (null == communityUser.getNickname()) {
            communityUser.setNickname(communityUser.getWechatNickname());
        }
        //微信头像转存oss
        communityUser.setWechatPortrait(imgSaveOss(communityUser.getWechatPortrait()));
        int i = communityUserMapper.insert(communityUser);
        if (i == 1) {
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("注册失败");
        }
    }

    @Override
    public ServerResponse userLogin(CommunityUser communityUser) {
        CommunityUser communityUser01 = new CommunityUser();
        communityUser01.setOpenId(communityUser.getOpenId());
        CommunityUser communityUser02 = communityUserMapper.selectOne(communityUser01);
        //未注册
        if (communityUser02 == null) {
            //预处理
            communityUser.setTruename("");
            communityUser.setUsermail("");
            communityUser.setPhone("");
            communityUser.setSlogan("");
            communityUser.setOrganization("");
            communityUser.setPosition("");
            communityUser.setPassword("");
            communityUser.setCreateTime(new Date());
            communityUser.setUpdateTime(new Date());
            communityUser.setGradeSign(1);
            communityUser.setScore(1);
            if (null == communityUser.getNickname()) {
                communityUser.setNickname(communityUser.getWechatNickname());
            }
            //微信头像转存oss
            communityUser.setWechatPortrait(imgSaveOss(communityUser.getWechatPortrait()));
            int j = communityUserMapper.insert(communityUser);
            CommunityUser communityUserResult = communityUserMapper.selectOne(communityUser);
            return ServerResponse.createBySuccess(communityUserResult);
            //已注册
        } else {
            //更新上次登录时间
            CommunityUser communityUserUpdate = new CommunityUser();
            communityUserUpdate.setId(communityUser02.getId());
            communityUserUpdate.setUpdateTime(new Date());
            communityUserMapper.updateById(communityUserUpdate);

            //判断上次登陆时间，超过12小时，则积分加1
            long currentTime = System.currentTimeMillis();
            if (currentTime - communityUser02.getUpdateTime().getTime() > 4320000) {
                this.AddScore(1, communityUser02.getOpenId());
            }

            return ServerResponse.createBySuccess(communityUser02);
        }

    }


    @Override
    public ServerResponse test(String imgUrl) {
        return ServerResponse.createBySuccess(imgSaveOss(imgUrl));
    }


    @Override
    public ServerResponse update(CommunityUser communityUser) {
//       对象预处理
        communityUser.setUpdateTime(new Date());
        EntityWrapper<CommunityUser> wrapper = new EntityWrapper<>();
        wrapper.eq("open_id", communityUser.getOpenId());
        // 更新个人信息
        communityUserMapper.update(communityUser, wrapper);
        return ServerResponse.createBySuccessMessage("修改成功");
    }


    @Override
    public ServerResponse list(String orderByColumn, String searchKey, String gradeSign, int pageNum, int pageSize) {
        EntityWrapper<CommunityUser> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(gradeSign)) {
            wrapper.eq("grade_sign", gradeSign);
        }
        if (StringUtils.isNotBlank(searchKey)) {
            wrapper.like("wechat_nickname", searchKey)
                    .or()
                    .like("nickname", searchKey)
                    .or()
                    .like("truename", searchKey);
        }
        wrapper.orderBy(orderByColumn, false);
        PageHelper.startPage(pageNum, pageSize);
        List<CommunityUser> list = communityUserMapper.selectList(wrapper);
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess("success", pageInfo);
    }


    @Override
    public ServerResponse panel_list() {
        Page<CommunityUser> page = new Page<>(1, 10);

        EntityWrapper<CommunityUser> wrapper_create = new EntityWrapper<>();
        wrapper_create.orderBy("create_time", false);
        List<CommunityUser> list_create = communityUserMapper.selectPage(page, wrapper_create);

        EntityWrapper<CommunityUser> wrapper_update = new EntityWrapper<>();
        wrapper_update.orderBy("update_time", false);
        List<CommunityUser> list_update = communityUserMapper.selectPage(page, wrapper_update);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list_create", list_create);
        map.put("list_update", list_update);

        return ServerResponse.createBySuccess("success", map);
    }

    @Override
    public CommunityUser detail(String wechatId) {
        CommunityUser communityUser = new CommunityUser();
        communityUser.setOpenId(wechatId);
        communityUser = communityUserMapper.selectOne(communityUser);
        return communityUser;
    }


    @Override
    public int SendSubscribeMessage() throws Exception {
        // 获取access_token
        String accessToken = RedisUtils.searchRedis(TOKEN_PREFIX);
        if (StringUtils.isEmpty(accessToken)) {
            String appId = PropertiesUtil.getProperty("miniProgram.pitaya.appid");
            String appSecrey = PropertiesUtil.getProperty("miniProgram.pitaya.appSecret");
            accessToken = accessTokenService.getAccessToken(appId, appSecrey);
            // 存入redis
            RedisUtils.expireSet(TOKEN_PREFIX, 7000000, accessToken);
        }

        //封装发送请求参数
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();

        Map<String, Object> subMap01 = new HashMap<>();
        subMap01.put("value", "新帖子待审核");

        Map<String, Object> subMap02 = new HashMap<>();
        subMap02.put("value", "审核中");

        Map<String, Object> subMap03 = new HashMap<>();
        String date4_Date = new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
        subMap03.put("value", date4_Date);

        map.put("thing1", subMap01);
        map.put("phrase2", subMap02);
        map.put("date4", subMap03);
        dataMap.put("data", map);

//        其他参数
//         dataMap.put("touser","oj4js4vmHDw66vlcCOrKXfEH6p1w");//李岩
//        dataMap.put("touser","oj4js4qOTF8IVPHL2tKu6dSX4pJ0");//赵艳松
        dataMap.put("touser", "oj4js4m8QbxojrSkUmKO1-eVwnbY");//苏玉

        dataMap.put("template_id", "fsAvZRGsQ6Fd8zBtbDqtqBFcziSDW5TvgeTSP8sPbq4");
        dataMap.put("page", "pages/AdministratorsList/AdministratorsList");

        Gson gson = new Gson();
        String parm = gson.toJson(dataMap);
        log.info(parm);
        //        发送请求
        String resultString = Httpsrequest.httpsRequest(url, "POST", parm);
        MsgSecCheckJson msgSecCheckJson = gson.fromJson(resultString, MsgSecCheckJson.class);
        System.out.println(resultString);
        return msgSecCheckJson.getErrcode();
    }

    @Override
    public CommunityUser getUserInfo(String wechatId) {
        CommunityUser communityUser = new CommunityUser();
        communityUser.setOpenId(wechatId);
        CommunityUser communityUserResult = communityUserMapper.selectOne(communityUser);

        return communityUserResult;
    }

    @Override
    public int AddScore(int Num, String wechatId) {
        CommunityUser communityUserTemp = new CommunityUser();
        communityUserTemp.setOpenId(wechatId);
        CommunityUser communityUser = communityUserMapper.selectOne(communityUserTemp);
//        未查找到此用户
        if (communityUser == null) {
            log.error("用户积分添加功能异常：未找到此用户：" + wechatId);
            return 0;
        }
        communityUser.setScore(communityUser.getScore() + Num);
        int i = communityUserMapper.updateById(communityUser);
        return i;
    }


//    ---------工具类-----


    /**
     * 创建FileItem
     *
     * @param imgUrl
     * @return
     */
    private String imgSaveOss(String imgUrl) {
        String tempName = System.currentTimeMillis() + ".jpg";
        System.out.println("tempName:" + tempName);
        String type = "nsi-community/UserPortrait/";
        try {
            ImageUtil.download(imgUrl, tempName, PropertiesUtil.getProperty("image.user.portrait"));
        } catch (Exception e) {
            System.err.println("转存图片出错：" + e);
            e.printStackTrace();
        }
        File file = new File(PropertiesUtil.getProperty("image.user.portrait") + tempName);

        System.out.println("file::" + PropertiesUtil.getProperty("image.user.portrait") + tempName);
        //对象存储上传
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        String OSS_Result = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, OSSClientConstants.BACKET_NAME, type);
        System.out.println("OSS_Result:" + OSS_Result);
        //删除本地文件
//        file.delete();
        String url = PropertiesUtil.getProperty("aliyun.image.url") + type + tempName;
        System.out.println(url);
        return url;
    }

}
